<template>
  <div class="container">
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <el-icon>
            <List/>
          </el-icon>
          <span>角色列表</span>
        </div>
      </template>

      <div class="query-form">
        <el-form :inline="true" :model="queryParams">
          <el-form-item label="角色名">
            <el-input
                v-model="search"
                placeholder="角色名"
                clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div class="table-toolbar">
        <el-button type="primary" @click="handleAdd" v-permission="['admin','insert_role']">
          <el-icon>
            <Plus/>
          </el-icon>
          添加角色
        </el-button>
        <el-button
            type="danger"
            :disabled="!selecteds.length"
            @click="handleBatchDelete"
            v-permission="['admin','delete_role']"
        >
          <el-icon>
            <Delete/>
          </el-icon>
          删除角色
        </el-button>
      </div>

      <!-- User Table -->
      <el-table
          :data="tableData"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
          height="calc(100vh - 420px)"
          v-loading="loading"
      >
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="roleId" label="ID" width="80"/>
        <el-table-column prop="roleCode" label="角色编码" width="150"/>
        <el-table-column prop="roleName" label="角色名"/>
        <el-table-column prop="dataType" label="数据权限" width="180">
          <template #default="scope">
            <DictSelect
                :model-value="scope.row.dataType"
                dicTypeCode="data_power_type"
                display-only
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320" fixed="right">
          <template #default="{ row }">
            <el-button v-permission="['admin','update_role']" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button v-permission="['admin','delete_role']" size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            <el-button v-permission="['admin','allocation_menu']" size="small" type="primary" @click="assignMenus(row)">分配菜单</el-button>
            <el-button v-permission="['admin','allocation_org']" size="small" type="primary" @click="assignOrgs(row)" v-if="row.dataType=='FLEXIBLY'">分配组织</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="queryParams.current"
            v-model:page-size="queryParams.size"
            :total="total"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleQuery"
            @current-change="fetchTableData"
        />
      </div>
    </el-card>
    <RoleDialog ref="RoleDialogRef" @submit="handleSubmit"></RoleDialog>
    <AssignMenus ref="AssignMenusRef" @submit="saveAssignMenus"></AssignMenus>
    <AssignOrgs ref="AssignOrgsRef" @submit="saveAssignOrgs"></AssignOrgs>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, watch} from 'vue'
import {
  Plus,
  Delete,
  List
} from '@element-plus/icons-vue'
import {tableInfoApi} from '@/api/core';
import {PageQuery, RelVo} from "@/types/api";
import {ElMessageBox, ElMessage} from 'element-plus'
import DictSelect from '@/components/DictSelect.vue'
import {RoleItem} from "@/views/role/role";
import RoleDialog from "./edit.vue"
import AssignMenus from "@/views/role/assignMenus.vue";
import AssignOrgs from "@/views/role/assignOrgs.vue";
import {menuApi} from "@/api/menu";
import {orgApi} from "@/api/org";

const RoleDialogRef = ref<InstanceType<typeof RoleDialog>>()
const AssignMenusRef = ref<InstanceType<typeof AssignMenus>>()
const AssignOrgsRef = ref<InstanceType<typeof AssignOrgs>>()
const search = ref('')
const queryParams = ref<PageQuery>({
  code: 'app_role',
  current: 1,
  size: 10,
  queryParams: [{
    paramName: "roleName",
    relation: "like",
    paramValue: ""
  }],
  querySorts: [{
    paramName: "roleId",
    order: "desc"
  }]
})
const tableData = ref<RoleItem[]>([])
const total = ref(0)
const loading = ref(false)
const selecteds = ref<RoleItem[]>([])

//搜索
const handleQuery = () => {
  queryParams.value.current = 1
  fetchTableData()
}

watch(search, (newVal) => {
  if (queryParams.value.queryParams && queryParams.value.queryParams[0]) {
    queryParams.value.queryParams[0].paramValue = newVal
  }
})

//查询
const fetchTableData = () => {
  loading.value = true
  tableInfoApi.page(queryParams.value).then(res => {
    total.value = res.data.total
    tableData.value = res.data.records
  }).finally(() => {
    loading.value = false
  })
}

//重置
const resetQuery = () => {
  queryParams.value.size = 10
  search.value = ''
  handleQuery()
}

//多选
const handleSelectionChange = (val: RoleItem[]) => {
  selecteds.value = val
}

//新增
const handleAdd = () => {
  RoleDialogRef.value?.openDialog()
}

//编辑
const handleEdit = (row: RoleItem) => {
  RoleDialogRef.value?.openDialog(row)
}

//保存数据
const handleSubmit = (data: RoleItem) => {
  tableInfoApi.saveOrUpdate("app_role", data).then(() => {
    ElMessage.success("保存角色成功")
    handleQuery()
  })
}

//删除单条
const handleDelete = (row: RoleItem) => {
  ElMessageBox.confirm(
      `是否确认删除用户 "${row.roleName}"？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    tableInfoApi.deleteById("app_role", "" + row.roleId).then(() => {
      ElMessage.success("删除用户成功")
      handleQuery()
    })
  }).catch(() => {
    // 点击取消，不做操作
  })
}

//批量删除
const handleBatchDelete = () => {
  if (!selecteds.value.length) return

  ElMessageBox.confirm(
      `是否确认删除选中的 ${selecteds.value.length} 个角色？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    const ids = selecteds.value.map(item => item.roleId).join(',')
    tableInfoApi.deleteByIds("app_role", ids).then(() => {
      ElMessage.success("批量删除角色成功")
      selecteds.value = []
      handleQuery()
    })
  }).catch(() => {
    // 点击取消，不做操作
  })
}

const assignMenus = (row: RoleItem) => {
  AssignMenusRef.value?.openDialog(row.roleId!)
}

const saveAssignMenus =(menus:string[],roleId:number)=>{
  const payload:RelVo<number,number> = {id:roleId,details:menus}
  menuApi.allocationMenu(payload).then(res=>{
    ElMessage.success("分配菜单成功")
  })
}

const assignOrgs = (row: RoleItem) => {
  AssignOrgsRef.value?.openDialog(row.roleId!)
}

const saveAssignOrgs =(orgs:string[],roleId:number)=>{
  const payload:RelVo<number,number> = {id:roleId,details:orgs}
  orgApi.allocationOrg(payload).then(res=>{
    ElMessage.success("分配组织成功")
  })
}

onMounted(() => {
  handleQuery()
})
</script>


<style scoped>
.container {
  display: flex;
  gap: 16px;
  height: 100%;
}

.table-card {
  flex: 1;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}


.query-form {
  margin-bottom: 16px;
}

.table-toolbar {
  margin-bottom: 16px;
}

.pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.selection-hint {
  margin-left: 12px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
}

:deep(.el-table) {
  --el-table-border-color: #eaeaea;
}

:deep(.el-tree) {
  --el-tree-node-hover-bg-color: #f5f7fa;
}
</style>